package com.fxd.service.impl;

import com.fxd.dao.IAccountDao;

import com.fxd.domain.account;
import com.fxd.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 账户的业务层实现类
 */
@Service("accountService")
@Transactional(propagation = Propagation.REQUIRED,readOnly = true)
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

//    private transactionManager txManager;
//
//    public void setTxManager(transactionManager txManager) {
//        this.txManager = txManager;
//    }

//    public void setAccountDao(IAccountDao accountDao) {
//        this.accountDao = accountDao;
//    }


    //需要读写型事物控制
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void transfer(String sourceName, String targetName, Float money) {

            //2.1,根据名称查询转出账户
            account source = accountDao.findAccountByName(sourceName);
            //2.2,根据名称查询转入账号
            account target = accountDao.findAccountByName(targetName);
            //2.3,转出账户减钱
            source.setMoney(source.getMoney() - money);
            //2.4,转入账号加钱
            target.setMoney((target.getMoney() + money));
            //2.5,更新转出账户
            accountDao.updateAccount(source);

            int i = 1 / 0;

            //2.6,更新转入账号
            accountDao.updateAccount(target);




    }

    public account findAccountById(Integer id) {
        account a = accountDao.findAccountById(id);
        return a;
    }

    public account findByName(String accountName) {
        try {
            //1,开启事物
            //txManager.begin();
            //2,执行操作
            account a = accountDao.findAccountByName(accountName);
            //3,提交事物
            //txManager.commit();
            //4,返回结果
            return a;
        } catch (Exception e) {
            //5,回滚操作
            //txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //6,释放连接
            //txManager.release();
        }
    }
}
